function ti = addlayer(ti, p, a)
% transimg::addlayer  - add a layer to an image

% global variables for storage
global tiobj ...
       tiobjlup;
   
% check arguments
lup = find(tiobjlup == ti.L);
if numel(lup) ~= 1
    error( ...
        'transimg:ObjectRemoved', ...
        'Object removed from global storage.' ...
    );
end
if nargin < 2 || ...
   ~isnumeric(p) || ...
    size(p, 1) ~= tiobj(lup).Height || ...
    size(p, 2) ~= tiobj(lup).Width || ...
   ~any([1, 3] == size(p, 3)) || ...
   (nargin > 2 && ...
    (~isa(a, 'double') || ...
     (numel(a) ~= 1 && ...
      (ndims(a) ~= 2 || ...
       size(a, 1) ~= size(p, 1) || ...
       size(a, 2) ~= size(p, 2)))))
    error( ...
        'transimg:InvalidCall', ...
        'Invalid call to transimg::addlayer.' ...
    );
end
if nargin < 3
    a = 1;
else
    a(isinf(a) | isnan(a) | a < 0) = 0;
    a(a > 1) = 1;
end

% convert pixel data if necessary
if ~isa(p, 'uint8')
    p = double(p(:, :, :));
    p(isinf(p) | isnan(p) | p < 0) = 0;
    while any(p > 1)
        p = (1 / 256) .* p;
    end
    p = uint8(round(255 .* p));
end

% reset IsRendered flag
tiobj(lup).IsRendered = false;

% add layer
tiobj(lup).Layer(end + 1).Alpha = a;
tiobj(lup).Layer(end).Pixel = p;
